﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using HIWSystem.Models;
using HIWSystem.Common;


namespace HIWSystem.ViewModel
{
    [MetadataType(typeof(AddPartNumberViewModel))]
    public class AddPartNumberViewModel : ViewModelBase,IDataErrorInfo
    {
        public AddPartNumberViewModel()
        {
            //消息标志token：ViewAlert，用于标识只阅读某个或者某些Sender发送的消息，并执行相应的处理，所以Sender那边的token要保持一致
            //执行方法Action：ShowReceiveInfo，用来执行接收到消息后的后续工作，注意这边是支持泛型能力的，所以传递参数很方便。
            Messenger.Default.Register<int>(this, "PrintConfigDesc", ReceiveAndFillLablePrintConfigId);
            Messenger.Default.Register<int>(this, "PackingPrintParamConfigDesc", ReceiveAndFillPackingPrintConfigId);
            Messenger.Default.Register<SnFormatEntity>(this, "SnFormatDefine", ReceiveAndFillSnFormatConfigId);
        }
        #region 属性
        /// <summary>
        /// 表单验证错误集合
        /// </summary>
        private Dictionary<String, String> dataErrors = new Dictionary<String, String>();

        private string pn;
        /// <summary>
        /// 机种
        /// </summary>
        [Required]
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        
        private string snFormat;
        /// <summary>
        /// 序列号格式
        /// </summary>
        ///[RegularExpression(@"(HIW(\w|\#){5}[A-HJ-NP-Y]{3}(\w|\?){5}|DX005(\w|\#){4}30(\w|\?){4}|DX006(\w|\#){4}31(\w|\?){4})$", ErrorMessage ="序列号格式不正确，正确的序列号格式如下:\nHIW#####AAB?????\nDX005####30????\nDX006####31????")]
        public string SnFormat
        {
            get { return snFormat; }
            set { snFormat = value; this.RaisePropertyChanged(() => SnFormat); }
        }
        private string unitCode="";
        /// <summary>
        /// 料号
        /// </summary>
        public string UnitCode
        {
            get { return unitCode; }
            set { unitCode = value; this.RaisePropertyChanged(() => UnitCode); }
        }
        private string kitCount="0";
        /// <summary>
        /// 子键数量
        /// </summary>
        [RegularExpression(@"^[0-9]*$",ErrorMessage ="输入的子键数量不是数字")]
        public string KitCount
        {
            get { return kitCount; }
            set { kitCount = value; this.RaisePropertyChanged(() => KitCount); }
        }
        private string printCopiesNum="1";
        /// <summary>
        /// 打印标签的份数
        /// </summary>
        [RegularExpression(@"^[1-9][0-9]{0,4}$", ErrorMessage = "请输入[1-99999]之间的数字")]
        //[RegularExpression(@"^\d+$", ErrorMessage = "输入的打印标签份数不是数字")]
        public string PrintCopiesNum
        {
            get { return printCopiesNum; }
            set { printCopiesNum = value; this.RaisePropertyChanged(() => PrintCopiesNum); }
        }
        private string perBoxNum = "1";
        /// <summary>
        /// 每箱包装数量
        /// </summary>
        [RegularExpression(@"^[1-9][0-9]*$",ErrorMessage ="请输入数字")]
        public string PerBoxNum
        {
            get { return perBoxNum; }
            set { perBoxNum= value; this.RaisePropertyChanged(() => PerBoxNum); }
        }

        private string pnType;
        /// <summary>
        /// 机种类型
        /// </summary>
        [RegularExpression(@"^(天线|滤波器|马达|无源器件)$",ErrorMessage ="请输入这(滤波器|天线|马达|无源器件)四个其中一个")]
        public string PnType
        {
            get { return pnType; }
            set { pnType = value; this.RaisePropertyChanged(() => PnType); }
        }
        private ObservableCollection<PartNumberEntity> pnSource;
        /// <summary>
        /// 机种数据源
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNSource
        {
            get { return pnSource; }
            set { pnSource = value; this.RaisePropertyChanged(() => PNSource); }
        }
        private int labelPrintConfigId=1;
        /// <summary>
        /// 标签打印配置Id
        /// </summary>
        public int LabelPrintConfigId
        {
            get { return labelPrintConfigId; }
            set { labelPrintConfigId = value; this.RaisePropertyChanged(() => LabelPrintConfigId); }
        }
        /// <summary>
        /// 包装打印配置Id
        /// </summary>
        private int packingPrintConfigId=2;

        public int PackingPrintConfigId
        {
            get { return packingPrintConfigId; }
            set { packingPrintConfigId = value; this.RaisePropertyChanged(() => PackingPrintConfigId); }
        }

        public string this[string columnName]
        {
            get
            {
                ValidationContext vc = new ValidationContext(this, null, null);
                vc.MemberName = columnName;
                var res = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
                var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
                if (res.Count > 0)
                {
                    AddDic(dataErrors, vc.MemberName);
                    return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
                }
                RemoveDic(dataErrors, vc.MemberName);
                return null;
            }
        }

        public string Error
        {
            get
            {
                return null;
            }
        }
        #endregion
        #region 命令
        private RelayCommand addPNCmd;

        public RelayCommand AddPNCmd
        {
            get 
            {
                if (addPNCmd==null)
                {
                    addPNCmd = new RelayCommand(AddPN);
                }
                return addPNCmd; 
            }
            set { addPNCmd = value; }
        }
        private RelayCommand SnFormatConfigcmd;

        public RelayCommand SnFormatConfigCmd
        {
            get {
                SnFormatConfigcmd = SnFormatConfigcmd ?? new RelayCommand(SnFormatConfig);
                return SnFormatConfigcmd; }
            set { SnFormatConfigcmd = value; }
        }

        private RelayCommand queryLabelPrintConfigCmd;

        public RelayCommand QueryLabelPrintConfigCmd
        {
            get 
            {
                if (queryLabelPrintConfigCmd==null)
                {
                    queryLabelPrintConfigCmd = new RelayCommand(QueryLabelPrintConfigHandler);
                }
                return queryLabelPrintConfigCmd; 
            }
            set { queryLabelPrintConfigCmd = value; }
        }
        private RelayCommand queryPackingPrintConfigCmd;

        public RelayCommand QueryPackingPrintConfigCmd
        {
            get 
            {
                if (queryPackingPrintConfigCmd==null)
                {
                    queryPackingPrintConfigCmd = new RelayCommand(QueryPackingPrintConfigHandler);
                }
                return queryPackingPrintConfigCmd;
            }
            set { queryPackingPrintConfigCmd = value; }
        }

        private RelayCommand unloadedPageCmd;

        public RelayCommand UnloadedPageCmd
        {
            get 
            {
                if (unloadedPageCmd==null)
                {
                    unloadedPageCmd = new RelayCommand(UnLoadedPage);
                }
                return unloadedPageCmd; 
            }
            set { unloadedPageCmd = value; }
        }

        #endregion
        #region 方法
        private void AddPN()
        {
            if (string.IsNullOrEmpty(KitCount))
            {
                MessageBox.Show("输入的子键数量不能为空!","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Warning);
                return;
            }
            if (string.IsNullOrEmpty(PerBoxNum))
            {
                MessageBox.Show("输入的包装数量不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (string.IsNullOrEmpty(PrintCopiesNum))
            {
                MessageBox.Show("输入的打印份数不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (string.IsNullOrEmpty(SnFormat))
            {
                MessageBox.Show("输入的序列号格式不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (snFormatEntity==null)
            {
                MessageBox.Show("序列号格式未定义，请点击配置按钮!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (dataErrors.Count == 0)
            {
                string retMsg = string.Empty;
                DataTable dtPN = new DataTable();
                PartNumberEntity partNumberEntity = new PartNumberEntity()
                {
                    PN = this.PN.ToUpper() ?? "",
                    SnFormat = this.SnFormat.ToUpper() ?? "",
                    UnitCode = this.UnitCode ?? "",
                    KitCount =Convert.ToInt32(this.KitCount),
                    PrintCopiesNum =Convert.ToInt32(this.PrintCopiesNum),
                    PnType = this.PnType ?? "",
                    LPCId = new LabelConfigEntity { Id = this.LabelPrintConfigId },
                    PPCId = new LabelConfigEntity { Id = this.PackingPrintConfigId },
                    PerBoxNum =Convert.ToInt32(this.PerBoxNum)
                };
                retMsg = BusinessProcess.AddPartNumber(partNumberEntity,snFormatEntity, out dtPN);
                if (retMsg.Split('|')[0] == "OK")
                {
                    PNSource = new ObservableCollection<PartNumberEntity>();
                    for (int i = 0; i < dtPN.Rows.Count; i++)
                    {
                        PNSource.Add(
                            new PartNumberEntity
                            {
                                PN = dtPN.Rows[i]["PartNumber"].ToString(),
                                SnFormat = dtPN.Rows[i]["SnFormat"].ToString(),
                                UnitCode = dtPN.Rows[i]["UnitCode"].ToString(),
                                KitCount = Convert.ToInt32(dtPN.Rows[i]["KitCount"] == DBNull.Value ? "0" : dtPN.Rows[i]["KitCount"].ToString() ?? "0"),
                                PrintCopiesNum = Convert.ToInt32(dtPN.Rows[i]["PrintCopiesNum"] == DBNull.Value ? "0" : dtPN.Rows[i]["PrintCopiesNum"].ToString() ?? "0"),
                                PnType = dtPN.Rows[i]["PnType"].ToString(),
                                PerBoxNum = Convert.ToInt32(dtPN.Rows[i]["PerBoxNum"] == DBNull.Value ? "0" : dtPN.Rows[i]["PerBoxNum"].ToString() ?? "0"),
                                CreateAt = dtPN.Rows[i]["CreateAt"].ToString(),
                            }); 
                    }
                    this.PN = "";
                    this.SnFormat = "";
                    this.UnitCode = "";
                    this.PnType = "";
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            } /*MessageBox.Show("验证通过！");*/
            else
                MessageBox.Show("信息输入有误！", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        /// <summary>
        /// 卸载页面
        /// </summary>
        private void UnLoadedPage()
        {
            //Messenger.Default.Unregister(this);
        }
        /// <summary>
        /// 查询标签打印配置参数
        /// </summary>
        private void QueryLabelPrintConfigHandler()
        {
            //显示页面
            ViewManager.Show("PrintConfigDesc");
        }
        /// <summary>
        /// 查询包装打印配置参数
        /// </summary>
        private void QueryPackingPrintConfigHandler()
        {
            //显示页面
            ViewManager.Show("PackingPrintParamConfigDesc");
        }

        /// <summary>
        /// 接收其它页面标签打印配置参数Id值并填充到页面中
        /// </summary>
        /// <param name="id"></param>
        private void ReceiveAndFillLablePrintConfigId(int id)
        {
            this.LabelPrintConfigId = id;
            //ViewManager.Close("PrintConfigDesc");
        }
        /// <summary>
        /// 接收其它页面标签打印配置参数Id值并填充到页面中
        /// </summary>
        /// <param name="id"></param>
        private void ReceiveAndFillPackingPrintConfigId(int id)
        {
            this.PackingPrintConfigId = id;
            //ViewManager.Close("PrintConfigDesc");
        }
        /// <summary>
        /// 这个方法可以作为多个CheckBox的Command处理函数
        /// </summary>
        /// <param name="c"></param>
        private void AutoGenerateSnFormat(CheckBox c)
        {
            if (c.IsChecked==true)
               this.SnFormat=BusinessProcess.GenerateSnFormat(c.Content.ToString());
        }
        /// <summary>
        /// 移除字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void RemoveDic(Dictionary<String, String> dics, String dicKey)
        {
            dics.Remove(dicKey);
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void AddDic(Dictionary<String, String> dics, String dicKey)
        {
            if (!dics.ContainsKey(dicKey)) dics.Add(dicKey, "");
        }
        /// <summary>
        /// 序列号格式配置
        /// </summary>
        private void SnFormatConfig()
        {
            ViewManager.ShowDialog("SnFormatDefine");
        }
        SnFormatEntity snFormatEntity = null;
        /// <summary>
        /// 接收来自子窗口序列号格式定义配置信息
        /// </summary>
        /// <param name="entity">序列号格式实体</param>
        private void ReceiveAndFillSnFormatConfigId(SnFormatEntity entity)
        {
            snFormatEntity = entity;
            StringBuilder strSnForamt = new StringBuilder();
            foreach (var cs in entity.ComponentSequence.Split('|'))
            {
                var type = entity.GetType();
                var property = type.GetProperty(cs);
                var propertyValue = property.GetValue(entity);
                strSnForamt.Append(propertyValue.ToString());
            }
            strSnForamt.Append(entity.SerialNumber);//最后添加上流水码部分
            //拼装字符串格式
            SnFormat = strSnForamt.ToString();
        }
        #endregion
    }
}
